/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sowrov.util.formatter;

import java.util.StringTokenizer;

/**
 *
 * @author Sowrov
 */
public class TimeFormatter {
    /**
     * If the String hourMinute is already a decimal formatted number then it will return as it is in decimal format.
     * If the string hourMinute is space or colon ':' separated number then it assume the 1st part as hour second part
     * as minute and convert it to decimal formatted time.
     * Invalid time will be always -1.0
     * @param hourMinute input string of hour and minute
     * @return decimal time
     */
    public double formateToDecimal(String hourMinute) {
        double decimalTime = -1.0; //init with invalid
        try{
            decimalTime = Double.parseDouble(hourMinute);
            if(decimalTime<0) {
                decimalTime = -1.0;
            }
            return decimalTime;
        } catch (NumberFormatException ex) {
            StringTokenizer strTok = new StringTokenizer(hourMinute, ": ");
//            System.out.println(strTok.countTokens());
            if ((strTok.countTokens() <= 0) || (strTok.countTokens() > 2)) {
                return decimalTime;
            } // end if

            try {
                int hour = Integer.parseInt(strTok.nextToken());
                int minute = 0;

                if (strTok.countTokens() == 1) {
                    minute = Integer.parseInt(strTok.nextToken());
                } // end if

                decimalTime = hour;
                decimalTime += Math.floor(minute / 60.0);
                minute %= 60;
                decimalTime += (minute / 60.0);
                if(decimalTime<0) {
                    decimalTime = -1.0;
                }
                return decimalTime;
            } // end try
            catch (final NumberFormatException exp) {
                return decimalTime; //-1
            } // end catch
        }
    }

    String decimalToStringTime(double time){
        String timeStr = "";
        int iTime = (int) time;
        timeStr += iTime;
        double minute = Math.rint((time - iTime)*60);
        iTime = (int) minute;
        timeStr += ":"+iTime;
        return timeStr;
    }

    public static void main(String args[]) {
        TimeFormatter tf = new TimeFormatter();
        for (int i=0; i<=60; i++) {
            double d = tf.formateToDecimal("5 "+i);
            System.out.println("Input: 5:"+i);
            System.out.println(d);
            System.out.println(tf.decimalToStringTime(d));
        }
    }
}
